<?php

require_once '../config.php';

session_start();

require_once '../function.php';

//TODO:5-分类筛选
$where = '1=1';
$search = '';
if (isset($_GET['category']) && $_GET['category'] !== 'all') {
    $where .= ' and posts.category_id = ' . $_GET['category'];
    $search .= '&category=' . $_GET['category'];
}

if (isset($_GET['status']) && $_GET['status'] !== 'all') {
    $where .= " and posts.status = '{$_GET['status']}'";
    $search .= '&status=' . $_GET['status'];
}

//TODO:2-展示页数
$size = 10; //每页10条数据
//根据url参数定义页数,从第一页开始
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;  //页数
$offset = ($page - 1) * $size;  //第几页总的条数


//TODO:3-总的条数
$total_count = (int)xiu_query_one("select 
					count(1) as num
					from posts
		inner join categories on posts.category_id = categories.id
		inner join users on posts.user_id = users.id
		where {$where};
		")['num'];

//最后一条数据时,应该展示几页  例如:198条-20页 201条-21页
$total_page = (int)ceil($total_count / $size);   // 总的条数 / 每页展示的条数


//TODO:4-页码

$show_num = 5;              //只展示5个页码
$interval = ($show_num - 1) / 2;  //间隔
$begin = $page - $interval; //开始码
$end = $page + $interval;   //结束码

//确保$begin不会小于1时
if ($begin < 1) {
    $begin = 1;
    $end = $show_num; //结束值应该同步
    if ($begin === 1) {
        $end = $show_num;
    }
}


//确保$end不会大于$total_page时
if ($end > $total_page) {
    $end = $total_page;
    $begin = $end - $show_num + 1;//开始值应该同步
    if ($end === $total_page) {
        $begin = $end - 4;
    }
}

//判断用户自定义page参数小于1时
if ($page < 1) {
    header('Location: /admin/posts.php?page=1' . $search);
}

//判断用户自定义page参数大于最大页数时
if ($page > $total_page) {
    header('Location: /admin/posts.php?page=' . $total_page . $search);
}


//TODO:1-查询数据
$posts = xiu_query_all("select posts.id,
					posts.title,
					users.nickname as user_name,
					categories.`name` as categories_name,
					posts.created,
					posts.status
					from posts
				
		inner join categories on posts.category_id = categories.id
		inner join users on posts.user_id = users.id
	    where {$where} 
		order by posts.created desc
		limit {$offset},{$size};");


$categories = xiu_query_all("select * from categories");


function convert_status($status)
{
    $dict = array(
        'published' => '已发布',
        'drafted' => '草稿',
        'trashed' => '回收站',
    );
    return isset($dict[$status]) ? $dict[$status] : '';
}

function convert_date($date)
{
    $time = strtotime($date);
    return date('Y-m-d <b\r> H:i:s', $time);
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>Posts &laquo; Admin</title>
    <link rel="stylesheet" href="/static/assets/vendors/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="/static/assets/vendors/font-awesome/css/font-awesome.css">
    <link rel="stylesheet" href="/static/assets/vendors/nprogress/nprogress.css">
    <link rel="stylesheet" href="/static/assets/css/admin.css">
    <script src="/static/assets/vendors/nprogress/nprogress.js"></script>
</head>
<body>
<script>NProgress.start()</script>

<div class="main">
    <?php include 'inc/navbar.php'; ?>

    <div class="container-fluid">
        <div class="page-title">
            <h1>所有文章</h1>
            <a href="post-add.php" class="btn btn-primary btn-xs">写文章</a>
        </div>
        <!-- 有错误信息时展示 -->
        <!-- <div class="alert alert-danger">
          <strong>错误！</strong>发生XXX错误
        </div> -->
        <div class="page-action">
            <!-- show when multiple checked -->
            <form class="form-inline" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                <select name="category" class="form-control input-sm">
                    <option value="all">所有分类</option>
                    <?php foreach ($categories as $item): ?>
                        <option value="<?php echo $item['id']; ?>"<?php echo isset($_GET['category']) && $_GET['category'] === $item['id'] ? ' selected' : ''; ?>><?php echo $item['name']; ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="status" class="form-control input-sm">
                    <option value="all">所有状态</option>
                    <option value="drafted"<?php echo isset($_GET['status']) && $_GET['status'] === 'drafted' ? ' selected' : ''; ?>>
                        草稿
                    </option>
                    <option value="published"<?php echo isset($_GET['status']) && $_GET['status'] === 'published' ? ' selected' : ''; ?>>
                        已发布
                    </option>
                    <option value="trashed"<?php echo isset($_GET['status']) && $_GET['status'] === 'trashed' ? ' selected' : ''; ?>>
                        回收站
                    </option>
                </select>
                <button class="btn btn-default btn-sm">筛选</button>
            </form>
            <a id="remove" class="btn btn-danger btn-sm" href="/admin/post-delete.php?id=<?php echo $_GET['id']; ?>"
               style="visibility: hidden">批量删除</a>
            <ul class="pagination pagination-sm pull-right">


                <li style="visibility: <?php echo $page === 1 ? 'hidden' : 'visible'; ?>"><a
                            href="?page=<?php echo $page === 1 ? (1) . $search : ($page - 1) . $search; ?>">上一页</a></li>

                <?php for ($i = $begin; $i <= $end; $i++): ?>
                    <?php if ($i >= 1): ?>
                        <li <?php echo $i === $page ? 'class="active"' : '' ?>><a
                                    href="?page=<?php echo $i . $search; ?>"><?php echo $i; ?></a></li>
                    <?php endif; ?>
                <?php endfor; ?>
                <li style="visibility: <?php echo $page === $total_page ? 'hidden' : 'visible'; ?>"><a
                            href="?page=<?php echo $page === $total_page ? $total_page . $search : ($page + 1) . $search; ?>">下一页</a>
                </li>

            </ul>
        </div>
        <table class="table table-striped table-bordered table-hover">
            <thead>
            <tr>
                <th class="text-center" width="40"><input type="checkbox" data-id="-1"></th>
                <th>标题</th>
                <th>作者</th>
                <th>分类</th>
                <th class="text-center">发表时间</th>
                <th class="text-center">状态</th>
                <th class="text-center" width="100">操作</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($posts as $item): ?>
                <tr>
                    <td class="text-center"><input type="checkbox" data-id="<?php echo $item['id']; ?>"></td>
                    <td><?php echo $item['title']; ?></td>
                    <td><?php echo $item['user_name']; ?></td>
                    <td><?php echo $item['categories_name']; ?></td>

                    <td class="text-center"><?php echo convert_date($item['created']); ?></td>
                    <td class="text-center"><?php echo convert_status($item['status']); ?></td>
                    <td class="text-center">
                        <a href="javascript:;" class="btn btn-default btn-xs">编辑</a>
                        <a href="/admin/post-delete.php?id=<?php echo $item['id']; ?>"
                           class="btn btn-danger btn-xs">删除</a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php $current_page = 'posts'; ?>
<?php include 'inc/sidebar.php'; ?>

<script src="/static/assets/vendors/jquery/jquery.js"></script>
<script src="/static/assets/vendors/bootstrap/js/bootstrap.js"></script>
<script>

    $(function () {
        let btn_remove = $('#remove');
        let inputAll = $('thead input');
        let input = $('tbody input');
        let tableInput = $('table input');
        let visibility = null;
        let arr = [];

        //table所有的input
        tableInput.on('change', function () {
            //利用h5自定义属性data-保存每个元素的id,存放到数组,便于删除数据
            let id = $(this).data('id');
            if ($(this).prop('checked')) {
                arr.push(id);
            } else {
                arr.splice(arr.indexOf(id), 1);
            }

            if ($('tbody input:checked').length === 0) {
                visibility = 'hidden';
            } else {
                visibility = 'visible';
            }

            btn_remove.css('visibility', visibility);
            //search: 搜索资源路径
            btn_remove.prop('search', '?id=' + arr);

        });

        //全选的input
        inputAll.on('change', function () {
            input.prop('checked', $(this).prop('checked'));
            if ($('thead input:checked').length === 0) {
                visibility = 'hidden';
                arr.length = 0;
            } else {
                visibility = 'visible';
            }
            btn_remove.css('visibility', visibility);
        });

        //单选的input
        input.on('change', function () {
            let checkedLen = $('tbody input:checked').length;
            let inputLen = input.length;
            inputAll.prop('checked', checkedLen === inputLen);
        });

    });


</script>

<script>NProgress.done()</script>
</body>
</html>
